package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.ServiceCapability;
import com.huaweicloud.sdk.iotda.v5.model.ServiceProperty;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductResponse;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataQueryDTO;
import com.zzyl.nursing.job.vo.IotMsgNotifyData;
import com.zzyl.nursing.job.vo.IotMsgService;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.DeviceInfo;
import com.zzyl.nursing.vo.DevicePropertyDataVo;
import com.zzyl.nursing.vo.HourlyDataVO;
import com.zzyl.nursing.vo.ListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 设备数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-29
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper,DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private IoTDAClient client;

    /**
     * 批量保存
     *
     * @param data
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData data) {
        //根据iotId查询设备'
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, data.getHeader().getDeviceId()));
        if(ObjectUtil.isEmpty(device)){
            log.info("设备不存在，设备id：{}",data.getHeader().getDeviceId());
            return;
        }

        //构建设备数据，可能会有多条
        List<IotMsgService> services = data.getBody().getServices();
        if(CollUtil.isEmpty(services)){
            log.info("设备数据为空");
            return;
        }
        //循序services
        services.forEach(s->{

            //处理上报时间
            String eventTimeStr = s.getEventTime();
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(localDateTime);

            List<DeviceData> list = new ArrayList<>();

            s.getProperties().forEach((k,v)->{
                //属性拷贝，从设备拷贝到设备数据
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId(null);
                deviceData.setCreateTime(null);
                deviceData.setFunctionId(k);
                deviceData.setDataValue(v+"");
                deviceData.setAlarmTime(eventTime);
                deviceData.setAccessLocation(device.getBindingLocation());
                list.add(deviceData);
            });
            //批量保存
            saveBatch(list);
            //保存到redis中
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,device.getIotId(), JSONUtil.toJsonStr(list));
        });
    }

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData)?1:0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData)?1:0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Override
    public ListVo queryDevicePropertyStatus(Device device) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_key", device.getProductKey());
        queryWrapper.eq("device_name", device.getDeviceName());
        Device device1 = deviceMapper.selectOne(queryWrapper);
        List<DevicePropertyDataVo> propertyStatusInfo = new ArrayList<>();
        //查询产品
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(device1.getProductKey());
        ShowProductResponse response;
        try {
            response = client.showProduct(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        for (ServiceCapability serviceCapability : serviceCapabilities) {
            List<ServiceProperty> properties = serviceCapability.getProperties();
            for (ServiceProperty property : properties) {
                DevicePropertyDataVo devicePropertyDataVo = new DevicePropertyDataVo();
                devicePropertyDataVo.setDataType(property.getDataType());
                devicePropertyDataVo.setIdentifier(property.getPropertyName());
                devicePropertyDataVo.setName(property.getDescription());
                devicePropertyDataVo.setUnit(property.getUnit());
                propertyStatusInfo.add(devicePropertyDataVo);
            }
        }
        String jsonStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, device1.getIotId());
        List<DeviceData> list = JSONUtil.toList(jsonStr, DeviceData.class);
        for (DevicePropertyDataVo devicePropertyDataVo : propertyStatusInfo) {
            if(StringUtils.isEmpty(jsonStr)){
                break;
            }
            for (DeviceData deviceData : list) {
                if (devicePropertyDataVo.getIdentifier().equals(deviceData.getFunctionId())) {
                    devicePropertyDataVo.setValue(deviceData.getDataValue());
                    devicePropertyDataVo.setTime(deviceData.getAlarmTime().
                            atZone(ZoneId.of("Asia/Shanghai")).
                            toInstant().toEpochMilli());
                }
            }
        }
        ListVo listVo = new ListVo();
        listVo.setPropertyStatusInfo(propertyStatusInfo);
        return listVo;
    }



    @Override
    public List<HourlyDataVO> queryDeviceDataListByDay(DeviceDataQueryDTO deviceDataQuerydto) {
        // 参数校验
        if (StringUtils.isBlank(deviceDataQuerydto.getIotId())) {
            throw new BaseException("设备ID不能为空");
        }
        if (StringUtils.isBlank(deviceDataQuerydto.getFunctionId())) {
            throw new BaseException("功能ID不能为空");
        }
        if (deviceDataQuerydto.getStartTime() == null || deviceDataQuerydto.getEndTime() == null) {
            throw new BaseException("时间范围不能为空");
        }

        // 设备存在性检查
        Long count = deviceMapper.selectCount(new QueryWrapper<Device>()
                .eq("iot_id", deviceDataQuerydto.getIotId()));
        if (count == 0) {
            throw new BaseException("设备不存在");
        }

        // 调用Mapper方法查询数据
        LocalDateTime startDateTime = deviceDataQuerydto.getStartDateTime();
        LocalDateTime endDateTime = deviceDataQuerydto.getEndDateTime();
        return deviceDataMapper.queryHourlyData(
                deviceDataQuerydto.getIotId(),
                deviceDataQuerydto.getFunctionId(),
                startDateTime,
                endDateTime
        );

    }
    @Override
    public List<HourlyDataVO> queryDeviceDataListByWeek(DeviceDataQueryDTO deviceDataQuerydto) {
        if (StringUtils.isBlank(deviceDataQuerydto.getIotId())) {
            throw new BaseException("设备ID不能为空");
        }
        if (StringUtils.isBlank(deviceDataQuerydto.getFunctionId())) {
            throw new BaseException("功能ID不能为空");
        }
        if (deviceDataQuerydto.getStartTime() == null || deviceDataQuerydto.getEndTime() == null) {
            throw new BaseException("时间范围不能为空");
        }

        // 设备存在性检查
        Long count = deviceMapper.selectCount(new QueryWrapper<Device>()
                .eq("iot_id", deviceDataQuerydto.getIotId()));
        if (count == 0) {
            throw new BaseException("设备不存在");
        }

        // 调用Mapper方法查询数据
        LocalDateTime startDateTime = deviceDataQuerydto.getStartDateTime();
        LocalDateTime endDateTime = deviceDataQuerydto.getEndDateTime();
        return deviceDataMapper.queryWeeklyData(
                deviceDataQuerydto.getIotId(),
                deviceDataQuerydto.getFunctionId(),
                startDateTime,
                endDateTime
        );
    }

}

